package com.tech.cloudapp.auth;


import com.tech.cloudapp.consta.CommConst;
import com.tech.cloudapp.exception.BusinessException;
import com.tech.cloudapp.model.CommonResponseDO;
import com.tech.cloudapp.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Map;

@Slf4j
@Component
public class CheckServiceAuthInteceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(checkWhileList(request))return true;

        Enumeration<String> enumeration = request.getHeaderNames();
        while(enumeration.hasMoreElements())
        {
            String key = enumeration.nextElement();
            log.info("key:{} value:{}",key,request.getHeader(key));
        }

        String token = request.getHeader(CommConst.TOKEN_KEY);
        if(StringUtils.isBlank(token) || token.equals("undefined"))
        {
            throw new BusinessException(CommonResponseDO.fail("500","token不能为空"));
        }

        if(!JwtUtil.validateToken(token))
        {
            throw new BusinessException(CommonResponseDO.fail("500","用户识别失败"));
        }


        return true;
    }


    private boolean checkWhileList(HttpServletRequest request)
    {
        String [] whileList = {"/user-info/register","/user-info/auth","/user-info/isexists"};
        for(String w : whileList)
        {
            String url = request.getRequestURI().toString().replace("/ques","").trim();
            if(url.equals(w))
            {
                return true;
            }
        }

        return false;
    }
}
